package com.kim.chapter10.http.xml.codec;

import com.kim.chapter10.http.xml.XStreamUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.nio.charset.Charset;

public abstract class AbstractHttpXmlEncoder<T> extends
        MessageToMessageEncoder<T> {

    final static String CHARSET_NAME = "UTF-8";
    final static Charset UTF_8 = Charset.forName(CHARSET_NAME);

    protected ByteBuf encode0(ChannelHandlerContext ctx, Object body)
            throws Exception {
        //将对象序列化为xml字符串
        String xmlStr = XStreamUtil.beanToXml(body);
        //将XML字符串包装为Netty的ByteBuf
        ByteBuf encodeBuf = Unpooled.copiedBuffer(xmlStr, UTF_8);
        return encodeBuf;
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        System.out.println(cause.getMessage());
    }

}
